<?php
namespace App\Admin\Export;

use App\Models\WorkTicket;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
use Dcat\Admin\Grid\Exporters\AbstractExporter;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

ini_set('memory_limit', '512M');
set_time_limit(0);
class WorkTicketExport extends AbstractExporter implements WithMapping,FromCollection,WithHeadings,WithStyles,WithColumnFormatting
{
    use Exportable;
    protected $fileName ='工单列表';
    protected $titles = [];

    public function __construct(){
        $this->fileName = $this->fileName.'_'.date('Y-m-d').'.xlsx';
        // 学校名称	姓名	身份证号	认证上网账号	联系电话	宿舍楼栋房号	报障时间	客服下单姓名	维护人员姓名	报障进度内容	完成时间
        $this->titles = [
            '学校名称',
            '姓名',
            '身份证号',
            '认证上网账号',
            '联系电话',
            '宿舍楼栋房号',
            '报障时间',
            '客服下单姓名',
            '维护人员姓名',
            '报障进度内容',
            '完成时间',
        ];

        parent::__construct();
    }

    public function headings(): array
    {
        return $this->titles;
    }

    public function export(){
        $this->download($this->fileName)->prepare(request())->send();
        exit;
    }

    public function collection()
    {
        return WorkTicket::with([
            'school',
            'schoolUser',
            'workUser',
            'details'
        ])->whereIn('id', collect($this->buildData())->pluck('id'))->get();
    }

    public function map($row): array
    {
        if(!$row instanceof WorkTicket) return [];
        return [
            $row->school->name,
            $row->schoolUser->real_name,
            $row->schoolUser->id_card,
            $row->schoolUser->account,
            $row->schoolUser->tel,
            $row->room_number,
            $row->created_at->format('Y-m-d H:i:s'),
            $row->adminUser->name,
            $row->workUser->real_name,
            $row->details->pluck('content')->implode('\n'),
            $row->finish_at ? $row->finish_at->format('Y-m-d H:i:s') : '',
        ];
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle('K')->getAlignment()->setWrapText(true);
    }

    public function columnFormats(): array
    {
        return [
            'G' => NumberFormat::FORMAT_DATE_YYYYMMDD, //日期
            'K' => NumberFormat::FORMAT_DATE_YYYYMMDD, //日期
        ];
    }

}